package com.bobi.tfca.ui.mainnavigation.home.structure

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModel
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.constants.PageElementIdConstant
import com.bobi.tfca.databinding.FragmentOrgStructureBinding
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.ResourceAPI
import com.bobi.tfca.ui.custom.ScaleImageView
import com.bobi.tfca.util.LogUtil
import com.bobi.tfca.util.RealPathUtil
import com.bumptech.glide.Glide
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

class OrgStructureFragment : BaseFragment<FragmentOrgStructureBinding, ViewModel>(
    FragmentOrgStructureBinding::inflate,
    null,
    true
) {
    private lateinit var imagePickerLauncher: ActivityResultLauncher<Intent>
    private lateinit var imageView: ImageView

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private val REQUIRED_PERMISSIONS = arrayOf(
        Manifest.permission.READ_EXTERNAL_STORAGE
    )

    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
            if (permissions.all { it.value }) {
                // 如果所请求的所有权限都被授予，则执行相应的操作，比如打开相册
            } else {
                // 如果有任何一个权限被拒绝，则可以向用户解释为什么需要这些权限，并提供一个再次请求的机会
                Toast.makeText(requireActivity(), "选择图片需要权限", Toast.LENGTH_SHORT).show()
            }
        }


    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun checkPermissions(): Boolean {
        val isAllGranted = REQUIRED_PERMISSIONS.all {
            ContextCompat.checkSelfPermission(
                requireContext(),
                it
            ) == PackageManager.PERMISSION_GRANTED
        }
        // 如果权限没有授予，请求权限
        if (!isAllGranted) {
            requestPermissionLauncher.launch(REQUIRED_PERMISSIONS)
            return false
        } else {
            return true
        }
    }

    // 在适当的时候调用请求权限的方法
    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun openPictureChooser() {
        if (checkPermissions()) {
            // 如果权限已被授予，则执行相应的操作，比如打开相册
            // 点击图片后，更改图片
            // 打开图片选择器
            val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            imagePickerLauncher.launch(intent)
        }
    }


    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    @SuppressLint("ResourceType", "UseRequireInsteadOfGet")
    override fun initFragment(
        binding: FragmentOrgStructureBinding,
        viewModel: ViewModel?,
        savedInstanceState: Bundle?
    ) {
        imageView = binding.zivOrgStructure
        // 设置上传按钮监听
        binding.btUpload.setOnClickListener {
            uploadImage()
        }
        // 设置菜单为监听的
        publicViewModel!!.apply {
            visiblePageElements.observe(viewLifecycleOwner) {
                binding.btUpload.visibility = getElementVisibility(PageElementIdConstant.FRAGMENT_ORG_STRUCTURE_BT_UPLOAD)
            }
        }

        // 注册图片选择器
        registerImagePickerResult()

        // 查询组织架构的图片
        getOrgStructurePicture()
    }

    private fun getOrgStructurePicture() {
        publicViewModel!!.apply {
            request(ResourceAPI::class.java).getOrgStructurePicture().getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")

                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val result = it.data
                                if (200 == result?.code) {
                                    val url = result.data ?: ""
                                    if (url.isNotBlank() && (!"null".equals(url))) {
                                        Glide.with(this@OrgStructureFragment).load(url)
                                            .placeholder(R.drawable.defaultbg_h)
                                            .into(imageView)
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private fun registerImagePickerResult() {
        imagePickerLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                if (result.resultCode == Activity.RESULT_OK) {
                    val selectedImageUri: Uri? = result.data?.data
                    selectedImageUri?.let {
                        val file = getFileFromUri(selectedImageUri)
                        val requestFile = RequestBody.create(MediaType.parse("image/*"), file)
                        val body =
                            MultipartBody.Part.createFormData("file", file!!.name, requestFile)
                        if (body != null) {
                            LogUtil.i("选择了图片")
                            // 将图片上传至服务器，由服务器上传至腾讯云，将返回的地址设为图片地址。
                            uploadImageToServer(
                                body
                            )
                        } else {
                            LogUtil.i("图片未选择")
                        }
                    }
                }
            }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun uploadImage() {
        openPictureChooser()
    }

    private fun getFileFromUri(uri: Uri): File? {
        val filePath = RealPathUtil.getRealPath(requireActivity(), uri)
        return if (filePath != null) File(filePath) else null
    }


    /**
     * 将图片上传至服务器，由服务器上传至腾讯云，将返回的地址设为图片地址。
     */
    private fun uploadImageToServer(
        file: MultipartBody.Part
    ) {
        publicViewModel!!.apply {
            request(ResourceAPI::class.java).saveOrgStructurePicture(file).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")

                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val result = it.data
                                if (result?.code == 200) {
                                    LogUtil.i("上传成功")
                                    val url = result.data ?: ""
                                    if (url.isNotBlank() && (!"null".equals(url))) {
                                        if (this@OrgStructureFragment.isAdded() && !this@OrgStructureFragment.isDetached()) {
                                            Glide.with(this@OrgStructureFragment).load(url)
                                                .placeholder(R.drawable.defaultbg_h)
                                                .into(imageView)
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}